package com.github.yoojia.flow.impl;

import com.github.yoojia.flow.Context;
import com.github.yoojia.flow.PiConfig;
import com.github.yoojia.flow.Plugin;
import com.parkingwang.lang.data.Config;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.wiringpi.Gpio;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 陈小锅 (yoojiachen@gmail.com)
 * @since 1.0.0
 */
public class PiGPIOControllerPlugin implements Plugin {

    private static final Logger LOGGER = LoggerFactory.getLogger(PiGPIOControllerPlugin.class);

    private GpioController mGpio;

    @Override
    public void onInit(Context context, Config configs) throws Exception{
        final int mode = PiConfig.PWM_MS.equals(configs.getString(PiConfig.NAME_PWM_MODE, PiConfig.PWM_MS).toUpperCase()) ?
                Gpio.PWM_MODE_MS : Gpio.PWM_MODE_BAL;

        final int range = configs.getInt(PiConfig.NAME_PWM_RANGE, 1024);
        final int clock = configs.getInt(PiConfig.NAME_PWM_CLOCK, 100);

        Gpio.pwmSetMode(mode);
        Gpio.pwmSetRange(range);
        Gpio.pwmSetClock(clock);

        LOGGER.info("Init PWN setting, PWMMode: {}, PWMRange: {}, PWMClock: {}",
                (mode == Gpio.PWM_MODE_MS ? PiConfig.PWM_MS : PiConfig.PWM_BAL),
                range,
                clock);
    }

    @Override
    public void onStart() {
        LOGGER.debug("Init GPIO Controller...");
        mGpio = GpioFactory.getInstance();
    }

    @Override
    public void onStop() {
        LOGGER.debug("Shutdown GPIO Controller...");
        if (mGpio != null
                && !mGpio.isShutdown()) {
            mGpio.shutdown();
        }
    }
}
